package com.example.myapplication

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Button
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.widget.LinearLayout
import android.widget.EditText
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.example.myapplication.utils.PermissionHelper
import android.util.Log

class MainActivity : AppCompatActivity() {
    
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: PatientAdapter
    private lateinit var emptyStateText: TextView
    private lateinit var userInfoText: TextView
    private lateinit var databaseHelper: DatabaseHelper
    private lateinit var spinnerFilterDepartment: android.widget.Spinner
    private lateinit var editTextFilterReporter: EditText
    private lateinit var editTextFilterStartDate: EditText
    private lateinit var editTextFilterEndDate: EditText
    private lateinit var editTextFilterKeyword: EditText
    private lateinit var buttonFilter: Button
    private var filterDepartmentList: List<String> = listOf()
    private val filterDateFormat = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault())
    private lateinit var swipeRefreshLayout: androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    
    @SuppressLint("SuspiciousIndentation")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // 请求 Android 13+ 通知权限
        PermissionHelper.requestNotificationPermission(this)
        
        // 启动实时通信服务
        startRealtimeService()
        // 新增：自动恢复登录状态
        val prefs = getSharedPreferences("user_prefs", MODE_PRIVATE)
        val isLoggedIn = prefs.getBoolean("is_logged_in", false)
        if (isLoggedIn && UserSession.currentUser == null) {
            val userId = prefs.getLong("user_id", 0)
            val username = prefs.getString("username", "") ?: ""
            val realName = prefs.getString("realName", "") ?: ""
            val department = prefs.getString("department", "") ?: ""
            val userTypeStr = prefs.getString("userType", "USER") ?: "USER"
            val userType = try { UserType.valueOf(userTypeStr) } catch (_: Exception) { UserType.USER }
            UserSession.currentUser = User(
                id = userId,
                username = username,
                password = "", // 密码不存本地
                realName = realName,
                department = department,
                userType = userType
            )
        }
        
        // 检查应用是否启用
        databaseHelper = DatabaseHelper(this)
        if (!databaseHelper.isAppEnabled()) {
            Toast.makeText(this, "应用正在更新中", Toast.LENGTH_LONG).show()
            finish()
            return
        }

        // 检查用户是否已登录
        if (UserSession.currentUser == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show()
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
            finish()
            return
        }

        // 初始化RecyclerView
        recyclerView = findViewById(R.id.recyclerViewPatients)
        recyclerView.layoutManager = LinearLayoutManager(this)
        
        // 初始化适配器
        adapter = PatientAdapter(
            emptyList(),
            onItemClick = { patient ->
                Toast.makeText(this, "患者: ${patient.name}", Toast.LENGTH_SHORT).show()
            },
            onDeleteClick = { patient ->
                val currentUser = UserSession.currentUser
                if (currentUser != null &&
                    (currentUser.userType == UserType.SUPER_SUPER_ADMIN ||
                            currentUser.userType == UserType.SUPER_ADMIN ||
                            currentUser.userType == UserType.DEPARTMENT_ADMIN ||
                            currentUser.id == patient.reportedBy)) {
                    deletePatient(patient)
                } else {
                    Toast.makeText(this, "您没有删除权限", Toast.LENGTH_SHORT).show()
                }
            },
            onEditClick = { patient ->
                val currentUser = UserSession.currentUser
                if (currentUser != null &&
                    (currentUser.userType == UserType.SUPER_SUPER_ADMIN ||
                            currentUser.userType == UserType.SUPER_ADMIN ||
                            currentUser.userType == UserType.DEPARTMENT_ADMIN ||
                            currentUser.id == patient.reportedBy)) {
                    val intent = Intent(this, AddPatientActivity::class.java)
                    intent.putExtra("edit_patient", patient)
                    startActivity(intent)
                } else {
                    Toast.makeText(this, "您没有编辑权限", Toast.LENGTH_SHORT).show()
                }
            }
        )
        recyclerView.adapter = adapter
        
        // 初始化UI组件
        emptyStateText = findViewById(R.id.textEmptyState)
        userInfoText = findViewById(R.id.textUserInfo)

        // 初始化筛选栏
        spinnerFilterDepartment = findViewById(R.id.spinnerFilterDepartment)
        editTextFilterReporter = findViewById(R.id.editTextFilterReporter)
        editTextFilterStartDate = findViewById(R.id.editTextFilterStartDate)
        editTextFilterEndDate = findViewById(R.id.editTextFilterEndDate)
        editTextFilterKeyword = findViewById(R.id.editTextFilterKeyword)
        buttonFilter = findViewById(R.id.buttonFilter)
        // 填充科室下拉
        filterDepartmentList = listOf("全部") + databaseHelper.getAllDepartments().map { it.name }
        val deptAdapter = android.widget.ArrayAdapter(this, android.R.layout.simple_spinner_item, filterDepartmentList)
        deptAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinnerFilterDepartment.adapter = deptAdapter
        // 日期选择器
        editTextFilterStartDate.setOnClickListener { showFilterDatePicker(editTextFilterStartDate) }
        editTextFilterEndDate.setOnClickListener { showFilterDatePicker(editTextFilterEndDate) }
        // 筛选按钮
        buttonFilter.setOnClickListener { applyPatientFilter() }

        // 初始化SwipeRefreshLayout
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout)
        swipeRefreshLayout.setOnRefreshListener {
            reloadPatientsWithFilter()
        }

        // 设置用户信息
        setupUserInfo()

        // 设置添加按钮
        val buttonAdd = findViewById<Button>(R.id.buttonAddPatient)
        buttonAdd?.setOnClickListener {
            try {
                // 检查用户登录状态
                if (UserSession.currentUser == null) {
                    Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show()
                    val intent = Intent(this, LoginActivity::class.java)
                    startActivity(intent)
                    return@setOnClickListener
                }
                
                // 检查存储权限（Android 12+可能不需要）
                try {
                    if (!PermissionHelper.checkStoragePermission(this)) {
                        PermissionHelper.requestStoragePermission(this)
                        Log.w("MainActivity", "存储权限未授予，但继续执行")
                        // 不强制退出，让用户继续尝试
                    }
                } catch (e: Exception) {
                    Log.e("MainActivity", "权限检查失败", e)
                    // 权限检查失败不阻止应用继续运行
                }
                
                // 检查数据库是否可用
                if (!databaseHelper.isDatabaseAvailable()) {
                    Toast.makeText(this, "数据库不可用，请重启应用", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                
            val intent = Intent(this, AddPatientActivity::class.java)
                startActivity(intent)
            } catch (e: Exception) {
                Log.e("MainActivity", "启动添加页面失败", e)
                Toast.makeText(this, "启动添加页面失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }

        // 设置退出按钮
        val buttonLogout = findViewById<Button>(R.id.buttonLogout)
        buttonLogout?.setOnClickListener {
            logout()
        }

        // 设置应用控制按钮（仅大总管理员可见）
        val buttonAppControl = findViewById<Button>(R.id.buttonAppControl)
        buttonAppControl?.setOnClickListener {
            showAppControlDialog()
        }

        // 设置用户管理按钮（仅管理员可见）
        val buttonUserManagement = findViewById<Button>(R.id.buttonUserManagement)
        buttonUserManagement?.setOnClickListener {
            showUserManagementDialog()
        }

        // 设置注册按钮
        val buttonRegister = findViewById<Button>(R.id.buttonRegister)
        buttonRegister?.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }

        // 设置科室管理按钮（仅管理员可见）
        val buttonDepartmentManagement = findViewById<Button>(R.id.buttonDepartmentManagement)
        buttonDepartmentManagement?.setOnClickListener {
            val intent = Intent(this, DepartmentManagementActivity::class.java)
            startActivity(intent)
        }

        // 设置数据导出按钮（仅管理员可见）
        val buttonDataExport = findViewById<Button>(R.id.buttonDataExport)
        buttonDataExport?.setOnClickListener {
            val intent = Intent(this, DataExportActivity::class.java)
            startActivity(intent)
        }

        // 设置通知按钮
        val buttonNotifications = findViewById<Button>(R.id.buttonNotifications)
        buttonNotifications?.setOnClickListener {
            val intent = Intent(this, NotificationActivity::class.java)
            startActivity(intent)
        }

        // 设置统计按钮（仅管理员可见）
        val buttonStatistics = findViewById<Button>(R.id.buttonStatistics)
        buttonStatistics?.setOnClickListener {
            val intent = Intent(this, StatisticsActivity::class.java)
            startActivity(intent)
        }

        // 设置服务器设置按钮
        val buttonServerSettings = findViewById<Button>(R.id.buttonServerSettings)
        buttonServerSettings?.setOnClickListener {
            val intent = Intent(this, ServerSettingsActivity::class.java)
            startActivity(intent)
        }

        // 根据用户权限显示/隐藏按钮
        setupButtonVisibility()

        // 加载患者数据
        loadPatients()
    }
    
    override fun onResume() {
        super.onResume()
        // 检查应用状态
        if (!databaseHelper.isAppEnabled()) {
            Toast.makeText(this, "应用正在更新中", Toast.LENGTH_LONG).show()
            logout()
            return
        }
        loadPatients()
        updateNotificationBadge()
    }

    private fun updateNotificationBadge() {
        val currentUser = UserSession.currentUser
        if (currentUser != null) {
            val unreadCount = databaseHelper.getUnreadNotificationCount(currentUser)
            val buttonNotifications = findViewById<Button>(R.id.buttonNotifications)
            
            if (unreadCount > 0) {
                buttonNotifications?.text = "消息通知 ($unreadCount)"
            } else {
                buttonNotifications?.text = "消息通知"
            }
        }
    }

    private fun setupUserInfo() {
        val currentUser = UserSession.currentUser
        if (currentUser != null) {
            val userTypeText = when (currentUser.userType) {
                UserType.SUPER_SUPER_ADMIN -> "大总管理员"
                UserType.SUPER_ADMIN -> "总管理员"
                UserType.DEPARTMENT_ADMIN -> "科室管理员"
                UserType.USER -> "普通用户"
                else -> "未知角色"
            }
            userInfoText.text = "当前用户: ${currentUser.realName} ($userTypeText) - ${currentUser.department}"
        }
    }

    private fun setupButtonVisibility() {
        val currentUser = UserSession.currentUser
        val buttonAppControl = findViewById<Button>(R.id.buttonAppControl)
        val buttonUserManagement = findViewById<Button>(R.id.buttonUserManagement)
        val buttonDepartmentManagement = findViewById<Button>(R.id.buttonDepartmentManagement)
        val buttonDataExport = findViewById<Button>(R.id.buttonDataExport)
        val buttonStatistics = findViewById<Button>(R.id.buttonStatistics)

        if (currentUser != null) {
            // 只有大总管理员可以看到应用控制按钮
            buttonAppControl?.visibility = if (currentUser.userType == UserType.SUPER_SUPER_ADMIN) {
                android.view.View.VISIBLE
            } else {
                android.view.View.GONE
            }

            // 管理员可以看到管理按钮
            val isAdmin = currentUser.userType == UserType.SUPER_SUPER_ADMIN ||
                    currentUser.userType == UserType.SUPER_ADMIN ||
                    currentUser.userType == UserType.DEPARTMENT_ADMIN

            buttonUserManagement?.visibility = if (isAdmin) {
                android.view.View.VISIBLE
            } else {
                android.view.View.GONE
            }

            buttonDepartmentManagement?.visibility = if (isAdmin) {
                android.view.View.VISIBLE
            } else {
                android.view.View.GONE
            }

            buttonDataExport?.visibility = if (isAdmin) {
                android.view.View.VISIBLE
            } else {
                android.view.View.GONE
            }

            buttonStatistics?.visibility = if (isAdmin) {
                android.view.View.VISIBLE
            } else {
                android.view.View.GONE
            }
        }
    }
    
    private fun loadPatients() {
        val currentUser = UserSession.currentUser
        if (currentUser != null) {
            val patients = databaseHelper.getPatientsByUserType(currentUser)

            if (patients.isNotEmpty()) {
        adapter.updatePatients(patients)
                emptyStateText.visibility = android.view.View.GONE
                recyclerView.visibility = android.view.View.VISIBLE
            } else {
                showEmptyState()
            }
        }
    }

    private fun reloadPatientsWithFilter() {
        swipeRefreshLayout.isRefreshing = true
        // 若有筛选条件则应用筛选，否则加载全部
        if (::spinnerFilterDepartment.isInitialized) {
            applyPatientFilter()
        } else {
            loadPatients()
        }
        swipeRefreshLayout.isRefreshing = false
    }

    private fun showEmptyState() {
        emptyStateText.text = "暂无患者信息\n请尝试更换筛选条件或添加新患者。"
        emptyStateText.visibility = android.view.View.VISIBLE
            recyclerView.visibility = android.view.View.GONE
    }

    private fun deletePatient(patient: Patient) {
        AlertDialog.Builder(this)
            .setTitle("确认删除")
            .setMessage("确定要删除患者 ${patient.name} 的信息吗？")
            .setPositiveButton("确定") { _, _ ->
                val result = databaseHelper.deletePatient(patient.id)
                if (result > 0) {
                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show()
                    loadPatients()
                } else {
                    Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showAppControlDialog() {
        val currentUser = UserSession.currentUser
        if (currentUser?.userType != UserType.SUPER_SUPER_ADMIN) {
            Toast.makeText(this, "您没有此权限", Toast.LENGTH_SHORT).show()
            return
        }

        val isEnabled = databaseHelper.isAppEnabled()
        val action = if (isEnabled) "停用" else "启用"

        AlertDialog.Builder(this)
            .setTitle("应用控制")
            .setMessage("确定要${action}应用吗？")
            .setPositiveButton(action) { _, _ ->
                databaseHelper.setAppStatus(!isEnabled, currentUser.id)
                if (!isEnabled) {
                    Toast.makeText(this, "应用已启用", Toast.LENGTH_SHORT).show()
        } else {
                    Toast.makeText(this, "应用已停用", Toast.LENGTH_SHORT).show()
                    logout()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showUserManagementDialog() {
        val currentUser = UserSession.currentUser
        if (currentUser == null) return

        val options = when (currentUser.userType) {
            UserType.SUPER_SUPER_ADMIN, UserType.SUPER_ADMIN -> arrayOf("查看所有用户", "查看待审批用户", "添加新用户")
            UserType.DEPARTMENT_ADMIN -> arrayOf("查看本科室用户", "查看待审批用户")
            UserType.USER -> return
        }

        AlertDialog.Builder(this)
            .setTitle("用户管理")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> showAllUsers()
                    1 -> showPendingUsers()
                    2 -> showAddUserDialog()
                    else -> { /* 默认情况 */ }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showAllUsers() {
        val users = databaseHelper.getAllUsers()

        if (users.isEmpty()) {
            Toast.makeText(this, "暂无用户数据", Toast.LENGTH_SHORT).show()
            return
        }

        val userList = users.joinToString("\n\n") { user ->
            "👤 ${user.realName}\n" +
                    "🏥 科室: ${user.department}\n" +
                                "🔑 角色: ${when(user.userType) {
                UserType.SUPER_SUPER_ADMIN -> "大总管理员"
                UserType.SUPER_ADMIN -> "总管理员"
                UserType.DEPARTMENT_ADMIN -> "科室管理员"
                UserType.USER -> "普通用户"
                else -> "未知角色"
            }}\n" +
                    "👤 用户名: ${user.username}\n" +
                    "✅ 状态: ${if (user.isApproved) "已审批" else "待审批"}\n" +
                    "📅 注册时间: ${user.registrationDate.ifEmpty { "未知" }}"
        }

        val dialog = AlertDialog.Builder(this)
            .setTitle("📋 所有用户列表 (共${users.size}人)")
            .setMessage(userList)
            .setPositiveButton("确定", null)
            .setNeutralButton("刷新") { _, _ ->
                showAllUsers()
            }
            .create()

        dialog.show()

        // 如果用户列表太长，设置滚动视图
        if (userList.length > 1000) {
            val scrollView = ScrollView(this)
            val textView = TextView(this)
            textView.text = userList
            textView.setPadding(50, 50, 50, 50)
            textView.textSize = 14f
            scrollView.addView(textView)

            dialog.setView(scrollView)
        }
    }
    
    private fun showPendingUsers() {
        val users = databaseHelper.getPendingUsers()
        if (users.isEmpty()) {
            Toast.makeText(this, "暂无待审批用户", Toast.LENGTH_SHORT).show()
            return
        }
        val context = this
        val linearLayout = LinearLayout(context)
        linearLayout.orientation = LinearLayout.VERTICAL
        val scrollView = ScrollView(context)
        scrollView.addView(linearLayout)
        users.forEach { user ->
            val userInfo = "${user.realName}（${user.department}）\n用户名: ${user.username}\n手机号: ${user.phone}\n类型: ${when(user.userType) {
                UserType.SUPER_SUPER_ADMIN -> "大总管理员"
                UserType.SUPER_ADMIN -> "总管理员"
                UserType.DEPARTMENT_ADMIN -> "科室管理员"
                UserType.USER -> "普通用户"
                else -> "未知角色"
            }}"
            val userLayout = LinearLayout(context)
            userLayout.orientation = LinearLayout.VERTICAL
            userLayout.setPadding(16, 16, 16, 16)
            val textView = TextView(context)
            textView.text = userInfo
            val editRemark = EditText(context)
            editRemark.hint = "审批备注(可选)"
            val approveBtn = Button(context)
            approveBtn.text = "审批通过"
            val rejectBtn = Button(context)
            rejectBtn.text = "拒绝"
            approveBtn.setOnClickListener {
                val currentUser = UserSession.currentUser
                if (currentUser != null) {
                    if (databaseHelper.approveUser(user.id, currentUser.id)) {
                        sendApprovalNotification(user, true, editRemark.text.toString())
                        Toast.makeText(context, "已通过", Toast.LENGTH_SHORT).show()
                        linearLayout.removeView(userLayout)
                    } else {
                        Toast.makeText(context, "审批失败", Toast.LENGTH_SHORT).show()
                    }
                }
            }
            rejectBtn.setOnClickListener {
                val currentUser = UserSession.currentUser
                if (currentUser != null) {
                    databaseHelper.deleteUser(user.id)
                    sendApprovalNotification(user, false, editRemark.text.toString())
                    Toast.makeText(context, "已拒绝", Toast.LENGTH_SHORT).show()
                    linearLayout.removeView(userLayout)
                }
            }
            val btnLayout = LinearLayout(context)
            btnLayout.orientation = LinearLayout.HORIZONTAL
            btnLayout.addView(approveBtn)
            btnLayout.addView(rejectBtn)
            userLayout.addView(textView)
            userLayout.addView(editRemark)
            userLayout.addView(btnLayout)
            linearLayout.addView(userLayout)
        }
        AlertDialog.Builder(context)
            .setTitle("待审批用户")
            .setView(scrollView)
            .setNegativeButton("关闭", null)
            .show()
    }
    
    // 审批/拒绝后推送系统通知
    private fun sendApprovalNotification(user: User, approved: Boolean, remark: String) {
        val db = databaseHelper
        val title = if (approved) "账号审批通过" else "账号被拒绝"
        val msg = if (approved) "您的账号已通过审批。" else "您的账号未通过审批。"
        val fullMsg = if (remark.isNotBlank()) "$msg\n备注: $remark" else msg
        
        val notification = Notification(
            title = title,
            message = fullMsg,
            type = NotificationType.APPROVAL,
            targetUserId = user.id,
            targetDepartment = user.department,
            createdBy = UserSession.currentUser?.id ?: 0
        )
        db.addNotification(notification)
    }
    
    private fun approveAllPendingUsers() {
        val currentUser = UserSession.currentUser
        if (currentUser == null) return

        val users = databaseHelper.getPendingUsers()
        var approvedCount = 0

        for (user in users) {
            if (databaseHelper.approveUser(user.id, currentUser.id)) {
                approvedCount++
            }
        }

        Toast.makeText(this, "已审批通过 $approvedCount 个用户", Toast.LENGTH_SHORT).show()
    }

    private fun showAddUserDialog() {
        // 这里可以跳转到添加用户界面
        Toast.makeText(this, "添加用户功能开发中...", Toast.LENGTH_SHORT).show()
    }

    private fun logout() {
        // 清除本地登录信息
        val prefs = getSharedPreferences("user_prefs", MODE_PRIVATE)
        prefs.edit().clear().apply()
        UserSession.currentUser = null
        Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show()
        val intent = Intent(this, LoginActivity::class.java)
        startActivity(intent)
        finish()
    }

    private fun showFilterDatePicker(editText: EditText) {
        val calendar = java.util.Calendar.getInstance()
        val datePickerDialog = android.app.DatePickerDialog(
            this,
            { _, year, month, dayOfMonth ->
                calendar.set(year, month, dayOfMonth)
                editText.setText(filterDateFormat.format(calendar.time))
            },
            calendar.get(java.util.Calendar.YEAR),
            calendar.get(java.util.Calendar.MONTH),
            calendar.get(java.util.Calendar.DAY_OF_MONTH)
        )
        datePickerDialog.show()
    }

    private fun applyPatientFilter() {
        val currentUser = UserSession.currentUser ?: return
        val department = spinnerFilterDepartment.selectedItem?.toString()?.takeIf { it != "全部" }
        val reporter = editTextFilterReporter.text.toString().trim().takeIf { it.isNotEmpty() }
        val startDate = editTextFilterStartDate.text.toString().trim().takeIf { it.isNotEmpty() }
        val endDate = editTextFilterEndDate.text.toString().trim().takeIf { it.isNotEmpty() }
        val keyword = editTextFilterKeyword.text.toString().trim().takeIf { it.isNotEmpty() }
        val patients = databaseHelper.getPatientsFiltered(currentUser, department, reporter, startDate, endDate, keyword)
        if (patients.isNotEmpty()) {
            adapter.updatePatients(patients)
            emptyStateText.visibility = android.view.View.GONE
            recyclerView.visibility = android.view.View.VISIBLE
        } else {
            adapter.updatePatients(emptyList())
            showEmptyState()
        }
    }
    
    /**
     * 启动实时通信服务
     */
    private fun startRealtimeService() {
        try {
            com.example.myapplication.realtime.RealtimeService.startService(this)
            Log.d("MainActivity", "实时通信服务启动成功")
        } catch (e: Exception) {
            Log.e("MainActivity", "启动实时通信服务失败", e)
            // 即使服务启动失败，也不影响主界面功能
            Toast.makeText(this, "实时通信服务启动失败，但应用功能正常", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 停止实时通信服务
     */
    private fun stopRealtimeService() {
        try {
            com.example.myapplication.realtime.RealtimeService.stopService(this)
            Log.d("MainActivity", "实时通信服务停止成功")
        } catch (e: Exception) {
            Log.e("MainActivity", "停止实时通信服务失败", e)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        when (requestCode) {
            PermissionHelper.NOTIFICATION_PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "通知权限已授予", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "通知权限被拒绝，可能影响推送功能", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 停止实时通信服务
        stopRealtimeService()
    }
} 